﻿using HXDNB.Infrastructure.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;

namespace HXDNB.DAL
{
    public class UserBLL
    {
        readonly Entities _e = new Entities();

        /// <summary>
        /// 缓存表PageRole数据
        /// </summary>
        private IEnumerable<PageRole> AllPages
        {
            get
            {
                List<PageRole> pages;
                if (CacheHelp.GetCache("AllPages") == null)
                {
                    pages = _e.PageRoles.ToList();
                    CacheHelp.SetCache("AllPages", pages);
                }
                else
                {
                    pages = (List<PageRole>)CacheHelp.GetCache("AllPages");
                }
                return pages;
            }
        }

        /// <summary>
        /// 根据ID查询单个用户信息
        /// </summary>
        public UserInfo Get(int id)
        {
            var info = (from i in _e.UserInfoes where i.Id == id select i).SingleOrDefault();
            return info;
        }

        /// <summary>
        /// 查询用户信息列表
        /// </summary>
        public IQueryable<UserInfo> GetList(string name)
        {
            var list = from i in _e.UserInfoes select i;
            if (string.IsNullOrWhiteSpace(name) == false)
                list = from i in list where i.Name.Trim() == name.Trim() select i;
            list = from i in list orderby i.Id select i;
            return list;
        }

        /// <summary>
        /// 获取绑定到下拉框中的角色列表
        /// </summary>
        public List<SelectListItem> GetListRoles()
        {
            return GetRoles().Select(item => new SelectListItem { Text = item.Value, Value = item.Key }).ToList();
        }

        /// <summary>
        /// 获取绑定到下拉框中的角色列表(由于本系统为固定三个角色,后期如需扩展可将此方法改进)
        /// </summary>
        public Dictionary<string, string> GetRoles()
        {
            return new Dictionary<string, string>
            { 
                {"1","管理员"},
                {"2","内部操作员"},
                {"3","外部操作员"}                                
            };
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        public int Add(UserInfo model)
        {
            string err = null;
            model.CreateTime = DateTime.Now;
            model.Pwd = DESEncrypt.Encrypt("123456");
            try
            {
                _e.UserInfoes.AddObject(model);
                _e.SaveChanges();
            }
            catch (Exception e)
            {
                model.Id = 0;
                err = e.Message;
            }
            finally
            {
                string msg = string.Format("添加用户[ID:{0},用户名:{1}]", model.Id, model.Name);
                new LogBLL().Add(LogType.用户日志, msg, model.Id > 0, err);
            }
            return model.Id;//添加成功返回自增ID
        }
        /// <summary>
        /// 修改角色
        /// </summary>
        public bool EditRole(UserInfo model)
        {
            bool result = false;
            string err = null;
            try
            {
                var info = Get(model.Id);
                if (info != null)
                {
                    info.Role = model.Role;
                    info.MeunRole = model.MeunRole;
                    _e.ObjectStateManager.ChangeObjectState(info, EntityState.Modified);
                    result = _e.SaveChanges() > 0;
                }
                else
                {
                    err = "用户不存在";
                }
            }
            catch (Exception e)
            {
                result = false;
                err = e.Message;
            }
            finally
            {
                string msg = string.Format("编辑用户[ID:{0},用户名:{1}]", model.Id, model.Name);
                new LogBLL().Add(LogType.用户日志, msg, result, err);
            }
            return result;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        public bool EditPwd(UserInfo model)
        {
            bool result = true;
            string err = null;
            try
            {
                var info = Get(model.Id);
                if (info != null)
                {
                    info.Pwd = DESEncrypt.Encrypt(model.Pwd);
                    _e.ObjectStateManager.ChangeObjectState(info, EntityState.Modified);
                    result = _e.SaveChanges() > 0;
                }
                else
                {
                    err = "用户不存在";
                }
            }
            catch (Exception e)
            {
                result = false;
                err = e.Message;
            }
            finally
            {
                string msg = string.Format("修改用户密码[ID:{0},用户名:{1}]", model.Id, model.Name);
                new LogBLL().Add(LogType.用户日志, msg, result, err);
            }
            return result;
        }
        /// <summary>
        /// 重置用户密码
        /// </summary>
        public bool Reset(int id)
        {
            bool result = false;
            string err = null;
            var info = Get(id);
            try
            {
                if (info != null)
                {
                    info.Pwd = DESEncrypt.Encrypt("123456");
                    _e.ObjectStateManager.ChangeObjectState(info, EntityState.Modified);
                    result = _e.SaveChanges() > 0;
                }
                else
                {
                    err = "用户不存在";
                }
            }
            catch (Exception e)
            {
                err = e.Message;
                result = false;
            }
            finally
            {
                string msg = string.Format("重置用户密码[ID:{0},用户名:{1}]", id, (info ?? new UserInfo()).Name);
                new LogBLL().Add(LogType.用户日志, msg, result, err);
            }
            return result;
        }
        /// <summary>
        /// 根据ID删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            bool result = false;
            string err = null;
            var info = Get(id);
            try
            {
                if (info != null)
                {
                    _e.UserInfoes.DeleteObject(info);
                    result = _e.SaveChanges() > 0;
                }
                else
                {
                    err = "用户不存在";
                }
            }
            catch (Exception e)
            {
                err = e.Message;
                result = false;
            }
            finally
            {
                info = info ?? new UserInfo();
                var msg = string.Format("删除用户[ID:{0},用户名:{1}]", info.Id, info.Name);
                new LogBLL().Add(LogType.用户日志, msg, result, err);
            }
            return result;
        }

        /// <summary>
        /// 根据ID查询页面信息
        /// </summary>
        public PageRole GetPage(int id)
        {
            var info = AllPages.FirstOrDefault(i => i.Id == id);
            return info;
        }

        /// <summary>
        /// 根据URL查询页面信息
        /// </summary>
        /// <returns></returns>
        public PageRole GetPageByUrl(Uri url)
        {
            var info = AllPages.FirstOrDefault(i => url.PathAndQuery.Equals(i.Url));
            return info ?? AllPages.FirstOrDefault(i => url.AbsolutePath.EndsWith(i.Url.Contains('?') ? i.Url.Remove(i.Url.IndexOf('?')) : i.Url));
        }

        /// <summary>
        /// 查询所有排序后的子页面列表
        /// </summary>
        /// <returns></returns>
        public List<PageRole> GetSonPages(int id)
        {
            var list = from i in AllPages
                       where i.ParentId == id
                       orderby i.Sort ascending
                       select i;
            return list.ToList();
        }

        /// <summary>
        /// 获取排序后的所有页面列表
        /// </summary>
        /// <returns></returns>
        public void GetAllPages(int startId, ref List<PageRole> pages)
        {
            var p = GetSonPages(startId);
            foreach (var item in p)
            {
                pages.Add(item);
                GetAllPages(item.Id, ref pages);
            }
        }

        /// <summary>
        /// 编辑角色权限
        /// </summary>
        /// <returns></returns>
        public bool EditPageRoles(string roleid, string pageValue)
        {
            const string strSql = @"update PageRole set roles=replace(roles,{0}+',','')
                              update PageRole set roles=roles+{0}+','
                              where id in (select ch from dbo.Str_Split({1},',') )";
            var result = false;
            string err = null;
            try
            {
                result = _e.ExecuteStoreCommand(strSql, roleid, pageValue) > 0;
                CacheHelp.RemoveAllCache("AllPages");
            }
            catch (Exception e)
            {
                result = false;
                err = e.Message;
            }
            finally
            {
                string msg = string.Format("编辑用户角色权限[角色ID:{0},页面ID:{1}]", roleid, pageValue);
                new LogBLL().Add(LogType.用户日志, msg, result, err);
            }
            return result;
        }
    }
}
